from flask import Blueprint, render_template, request, session, redirect, url_for
from .db import get_db
from .decorator import login_required

clazz_bp = Blueprint('clazz', __name__)

@clazz_bp.route('/clazz', methods=['GET'])
@login_required
def index():
    clazzes = get_db().execute("SELECT * FROM clazz order by `id` desc").fetchall()
    return render_template('clazz/index.html', clazzes=clazzes)

@clazz_bp.route('/clazz/add', methods=['GET'])
@login_required
def add():
    return render_template('clazz/add.html')

@clazz_bp.route('/clazz/edit', methods=['GET'])
@login_required
def edit():
    id = int(request.args.get('id'))
    clazz = get_db().execute("select * from clazz where id=?", (id,)).fetchone()
    return render_template('clazz/edit.html', clazz=clazz)

@clazz_bp.route('/clazz/delete', methods=['GET'])
@login_required
def delete():
    id = int(request.args.get('id'))
    get_db().execute("delete from clazz where id=?", (id,))
    get_db().commit()
    return redirect(url_for('clazz.index'))

@clazz_bp.route('/clazz/save', methods=['POST'])
@login_required
def save():
    name = request.form['name']
    students_count = request.form['students_count']
    get_db().execute('insert into clazz (name, students_count) values (?, ?)', (name, students_count))
    get_db().commit()
    return redirect(url_for('clazz.index'))

@clazz_bp.route('/clazz/update', methods=['POST'])
@login_required
def update():
    name = request.form['name']
    students_count = request.form['students_count']
    id =  request.form['id']
    get_db().execute('update clazz set name=?, students_count=? where id=?', (name,students_count,id,))
    get_db().commit()
    return redirect(url_for('clazz.index'))

